<template>
    <el-dialog
            :title="title"
            :visible.sync="isVisible"
            :width="width"
            :before-close="handleClose"
            :lock-scroll="true"
            :close-on-click-modal="false"
            custom-class="pub_dialog"
            @open="getData"
    >
        <formTitle title="任务信息"/>
        <VForm
                ref="vformComponents"
                :form="formData.form"
                :options="formData.options"
                :rules="formData.rules"
                :labelWidth="formData.labelWidth"
                :rowspan="rowspan"
        ></VForm>
        <formTitle title="排查治理信息"/>
        <el-card class="box-card" v-for="(item,index) in formCheckData" :key="index">
            <VForm
                    ref="vformComponents2"
                    :form="item.form"
                    :options="item.options"
                    :rules="item.rules"
                    :labelWidth="item.labelWidth"
                    :rowspan="rowspan"
            ></VForm>
            <div class="center-btn">
                <el-button type="danger" icon="el-icon-delete" @click="deleteCheckData(index)">删除该排查信息</el-button>
            </div>
        </el-card>
        <div class="center-btn" style="margin-top:20px">
            <el-button type="success" icon="el-icon-plus" @click="addCheckData">添加一条排查信息</el-button>
        </div>
        <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </span>
    </el-dialog>
</template>

<script>
    import { riskPatrolPlanDetail,
            riskPatrolPlanUpdate,
            riskPatrolPlanAdd } from '@/api/risk/riskPatrolPlan'
    import VForm from "@/components/VForm/index";
    import formTitle from '@/components/FormTitle/formTitle.vue';

    export default {
        components: {
            VForm,formTitle
        },
        props: {
            width: {
                type: String,
                default: "70%",
            },
            title: {
                type: String,
                default: "详情",
            },
            id:{},
            openType:{
                type:String,
                default:"add"
            },
            dialogVisible: {
                type: Boolean,
                default: false
            },
            areaTreeOptions:{}
        },
        watch: {
            'areaTreeOptions':{
              handler(newVal, oldVal) {
                this.formData.options.forEach(t=> {
                  if (t.key == 'areaCode') {
                    t.option.data = newVal
                  }
                })
                console.log("wstchaa=========this.areaTreeOptions",this.areaTreeOptions)
              },
              deep: true,
              immediate: true
            },

            'width': {
                handler(newVal, oldVal) {
                    console.log('newVal===',newVal, oldVal)
                    let w = this.width.split('%')[0]
                    if(w>=60){
                        this.rowspan = 2
                    }else{
                        this.rowspan = 1
                    }
                },
                deep: true,
                immediate: true
            },
            'yearOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='year'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },
            'statusOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='status'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },
        },
        computed: {
            isVisible: {
                get() {
                    return this.dialogVisible
                },
                set() {
                    this.close()
                }
            }
        },
        data() {
            return {
                rowspan:1,
                dict:{},
                formData: {
                    form: {
                            planName:"",
                            address:"",
                            year:"",
                            content:"",
                            startDate:"",
                            endDate:"",
                            lon:"",
                            lat:"",
                            provinceCode:"",
                            cityCode:"",
                            countyCode:"",
                            areaCode:"",
                            status:"",
                            updateTime:"",
                            updateBy:"",
                        },
                    options: [
                                   {
                                       title: "任务名称",
                                       key: "planName",
                                       type: "text",
                                   },

                                {
                                    title: "年份",
                                    key: "year",
                                    type: "select",
                                    multiple:false,
                                    option: {
                                        data: this.yearOptions,
                                        props: {
                                            key: "id", // 指定key对应data的字段
                                            label: "label", // 指定label对应data的字段
                                            value: "value", // 指定value对应data的字段
                                        },
                                    },
                                },

                                  {
                                    title: "任务城市",
                                    key: "areaCode",
                                    type: "gdAreaSelect",
                                  },
                                   {
                                       title: "任务内容",
                                       key: "content",
                                       type: "textarea",
                                        columnWidth: 'w100max'
                                   },
                                   {
                                       title: "任务开始日期",
                                       key: "startDate",
                                       type: "date",
                                   },
                                   {
                                       title: "任务截止日期",
                                       key: "endDate",
                                       type: "date",
                                   },



                                    {
                                      title: "任务状态",
                                      key: "status",
                                      type: "select",
                                      multiple:false,
                                      option: {
                                        data: this.statusOptions,
                                        props: {
                                          key: "id", // 指定key对应data的字段
                                          label: "label", // 指定label对应data的字段
                                          value: "value", // 指定value对应data的字段
                                        },
                                      },
                                    },
                                    /**
                                   {
                                       title: "更新时间",
                                       key: "updateTime",
                                       type: "date",
                                   },
                                   {
                                       title: "更新人",
                                       key: "updateBy",
                                       type: "text",
                                   },
                                     **/
                    ],
                    rules: {
                        planName :[
                          {required: true, message: "请输入",max:64, message: '长度最大为64个字符', trigger: 'blur'}
                        ],
                        address :[
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        year :[
                        ],
                        content :[
                          {max:1024, message: '长度最大为1024个字符', trigger: 'blur'}
                        ],
                        startDate :[
                        ],
                        endDate :[
                        ],
                        lon :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        lat :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],

                        areaCode :[

                        ],
                        status :[
                        ],
                        updateTime :[
                        ],
                        updateBy :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                    },
                    labelWidth: "100px",
                },
                formCheckData: [],
                formData2: {
                    form: {
                            executeDate:"",
                            content:"",
                            status:"",
                            pic:[],
                        },
                    options: [
                                {
                                    title: "排查日期",
                                    key: "executeDate",
                                    type: "date",
                                },
                                {
                                    title: "排查进度",
                                    key: "status",
                                    type: "select",
                                    multiple:false,
                                    option: {
                                        data: this.patrolPlanExecuteStatusOptions,
                                        props: {
                                            key: "id", // 指定key对应data的字段
                                            label: "label", // 指定label对应data的字段
                                            value: "value", // 指定value对应data的字段
                                        },
                                    },
                                },
                                {
                                    title: "排查内容",
                                    key: "content",
                                    type: "textarea",
                                    columnWidth: 'w100max',
                                },
                                {
                                    title:'文件上传',
                                    key:'pic',
                                    type:'file',
                                    fileType:'image',
                                    uploadTextTip:'仅限上传图片',
                                    listType:'picture-card',
                                },
                    ],
                    rules: {
                        executeDate:[
                          {required: true, trigger: 'blur'}
                        ],
                        content :[
                          {max:1024, message: '长度最大为1024个字符', trigger: 'blur'}
                        ],
                        status :[
                        ],
                        updateTime :[
                        ],
                    },
                    labelWidth: "140px",
                },
            // 字典
                yearOptions:[],
                statusOptions:[],
                patrolPlanExecuteStatusOptions:[],
            };
        },
        methods: {
            submitFormat(){
            },
            loadFormat(){
            },
            getCheckBoxData(value,option,type){
                if(type=="submit"){
                    if(value.length==0){
                        return null
                    }
                    let temp = [];
                    value.forEach(t=>{
                        let item = option.find(x=> x.label == t)
                    if(item!=undefined){
                        temp.push(item.value)
                    }
                })
                    return temp.join(",")
                }else {
                    if(!value){
                        return []
                    }else {
                        let data = value.split(",")
                        let temp = []
                        data.forEach(t=>{
                            let item = option.find(x=> x.value == t)
                        if(item!=undefined){
                            temp.push(item.label)
                        }
                    })
                        return temp
                    }
                }
            },
            sure(){
                console.log('sure===',this.formData.form)
                this.$refs.vformComponents.$refs.form.validate().then(res=>{
                    if(this.formData.form.areaCode){
                      let temp  = this.formData.form.areaCode
                      this.formData.form.provinceCode = temp[0]
                      this.formData.form.cityCode = temp[1]
                      this.formData.form.countyCode = temp[2]
                      if(this.formData.form.countyCode!=''){
                        this.formData.form.areaCode = temp[2]
                      }else{
                        if(this.formData.form.cityCode!=''){
                          this.formData.form.areaCode = temp[1]
                        }else{
                          this.formData.form.areaCode =temp[0]
                        }
                      }
                    }
                    this.submitFormat()
                    if(this.openType == "add"){
                        this.add()
                    }else{
                        this.update()
                    }
                })
            },
            add(){
                this.formData.form.id = null
                this.formData.form.delFlag=0;
                let formCheckReqdata = this.formCheckData.map(t=>{
                    return t.form
                })
                formCheckReqdata.forEach(t=>{
                  t.pic = JSON.stringify(t.pic)
                })
                let reqdata = {
                    ...this.formData.form,
                    executeList: formCheckReqdata,
                }
                riskPatrolPlanAdd(reqdata).then(res=>{
                    if(res.code==200){
                    this.$message({
                        message: this.$t('tips.createSuccess'),
                        type: 'success'
                    })
                    this.closeSuccess()
                    }else{
                    this.$message({
                        message: this.$t('tips.systemException'),
                        type: 'error'
                    })
                    }
                })
            },
            update(){
                let formCheckReqdata = this.formCheckData.map(t=>{
                    return t.form
                })
                console.log(formCheckReqdata)
                formCheckReqdata.forEach(t=>{
                    t.pic = JSON.stringify(t.pic)
                })
                let reqdata = {
                    ...this.formData.form,
                    executeList: formCheckReqdata,
                }
                
                   riskPatrolPlanUpdate(reqdata).then(res=>{
                        if(res.code==200){
                        this.$message({
                             message: this.$t('tips.updateSuccess'),
                            type: 'success'
                        })
                        this.closeSuccess()
                      }else{
                        this.$message({
                            message: this.$t('tips.systemException'),
                            type: 'error'
                        })
                     }
                })
            },
            cancel(){
                this.close()
            },
            handleClose(done) {
                done()
                this.close()
            },
            closeSuccess(){
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$emit('success')
            },
            close(){
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$emit('close')
            },
            getData(){
                this.yearOptions = []
                this.$commonJs.filterDataDict("patrolPlanYear",this.yearOptions )

                this.statusOptions = []
                this.$commonJs.filterDataDict("patrolPlanStatus",this.statusOptions )

                this.patrolPlanExecuteStatusOptions = []
                this.$commonJs.filterDataDict("patrolPlanExecuteStatus",this.patrolPlanExecuteStatusOptions )
                this.formData2.options.forEach(t=>{
                    if(t.key=='status'){
                        t.option.data = this.patrolPlanExecuteStatusOptions
                    }
                })

                this.formCheckData = []

                if(this.openType!="add"){
                    riskPatrolPlanDetail(this.id).then(res=>{
                        if(res.code==200){
                            this.formData.form = res.data
                            res.data.executeList.forEach(t=>{
                                if(t.pic === null){
                                    t.pic = []
                                }else{
                                    t.pic = JSON.parse(t.pic).map(item=>{
                                        return{
                                            name:item.name,
                                            url: process.env.VUE_APP_BASE_API + 'file/api/download/'+item.fileId,
                                            uid: item.uuid,
                                            fileId: item.fileId,
                                        }
                                    })
                                }
                            })
                            this.formCheckData = res.data.executeList.map(t=>{
                                return {
                                    form:t,
                                    options:JSON.parse(JSON.stringify(this.formData2.options)),
                                    rules:JSON.parse(JSON.stringify(this.formData2.rules)),
                                    labelWidth:this.formData2.labelWidth,
                                }
                            })
                            this.formData.form.areaCode = [
                              res.data.provinceCode,
                              res.data.cityCode,
                              res.data.countyCode,
                            ];
                            this.loadFormat()
                         }else{
                            this.$message({
                                message: this.$t('tips.systemException'),
                                type: 'error'
                            })
                        }
                    })
                }
            },
            addCheckData(){
                const formData = JSON.parse(JSON.stringify(this.formData2))
                this.formCheckData.push(formData)
            },
            deleteCheckData(index){
                this.formCheckData.splice(index,1)
            },
        },
    };
</script>

<style lang="scss" scoped>

.box-card{
    margin-bottom: 10px;
}
.center-btn{
    text-align: center;
}

::v-deep .el-button + .el-button{
    margin-left: 10px !important;
}
</style>
